//
//  LLPresentationController.m
//
//  Created by 李叶夫 on 2017/3/19.
//  Copyright © 2017年 李叶夫. All rights reserved.
//

#import "LLPresentationController.h"

@interface LLPresentationController ()

@property (strong, nonatomic) UIView *bgView;


@end

@implementation LLPresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController
{
    if ([presentedViewController isKindOfClass:[LLPresentationBottomViewController class]])
    {
        LLPresentationBottomViewController *vc = (LLPresentationBottomViewController *)presentedViewController;
        self.controllerHeight = vc.controllerHeight ? vc.controllerHeight : [UIScreen mainScreen].bounds.size.height;
    }
    else
    {
        self.controllerHeight = [UIScreen mainScreen].bounds.size.height;
    }
    return [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
}

- (void)presentationTransitionWillBegin
{
    self.bgView.alpha = 0;
    [self.containerView addSubview:self.bgView];
    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.alpha = 1.0;
    }];
}

- (void)dismissalTransitionWillBegin
{
    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.alpha = 0;
    }];
}

- (void)dismissalTransitionDidEnd:(BOOL)completed
{
    if (completed) {
        [self.bgView removeFromSuperview];
    }
}

- (CGRect)frameOfPresentedViewInContainerView
{
    return CGRectMake(0, [UIScreen mainScreen].bounds.size.height - self.controllerHeight, [UIScreen mainScreen].bounds.size.width, self.controllerHeight);
}

#pragma mark - lazy
- (UIView *)bgView
{
    if (!_bgView)
    {
        _bgView = [[UIView alloc] initWithFrame:self.containerView.bounds];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return _bgView;
}

@end


@implementation LLPresentationBottomViewController

- (void)presentBottomViewControllerFromController:(UIViewController *)controller
{
    self.modalPresentationStyle = UIModalPresentationCustom;
    self.transitioningDelegate = self;
    [controller presentViewController:self animated:YES completion:nil];
}

- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    LLPresentationController *c = [[LLPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    return c;
}

@end


